<?php
namespace App\Services;
use Illuminate\Support\Facades\Request;

/**
 * Created by PhpStorm.
 * User: User
 * Date: 2017/7/31
 * Time: 16:23
 */
class Login
{
    public static $errorMessage = '';

    /**
     * 验证用户名密码
     * @param $account
     * @param $pass
     * @param $user_index
     * @return bool
     */
    public static function checkLogin($account , $pass , $user_index){
        $users = config('constant.users')[$user_index];
        if(!isset($users[$account])){
            self::$errorMessage = '用户不存在';
            return false;
        }
        if($users[$account]['password'] != $pass){
            self::$errorMessage = '密码错误';
            return false;
        }
        self::$errorMessage = 'success';
        return $users[$account];
    }

    /**
     * 登录成功后保存用户的session信息
     * @param $user_arr
     * @return bool
     */
    public static function setValue($user_arr){
        Request::session()->put('user_info' , json_encode($user_arr));//用户信息
        Request::session()->put('user_menus' , json_encode(self::getUserMenu($user_arr['is_super'])));//用户菜单
        Request::session()->save();
        return true;
    }

    /**
     * 获取用户的菜单
     * @param $is_super
     * @return mixed
     */
    public static function getUserMenu($is_super){
        $menus = config('constant.menus')['long'];
        if(!$is_super){
            return self::getMenu($menus);
        }
        return $menus;
    }

    /**
     * 删除只能超级管理员看的菜单
     * @param $menus
     * @return mixed
     */
    private static function getMenu(&$menus){
        foreach($menus as $key=>&$value){
            if(isset($value['child_menus']) && $value['child_menus']){
                self::getMenu($value['child_menus']);
            }else{
                if($value['is_super_only']){
                    unset($menus[$key]);
                }
            }
        }
        return $menus;
    }
}